const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const { User } = require('./User');

const Payment = sequelize.define('payment', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  orderId: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'user',
      key: 'id'
    }
  },
  materialOrderId: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'materialOrder',
      key: 'id'
    }
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    validate: {
      min: 0.01
    }
  },
  coins: {
    type: DataTypes.INTEGER,
    allowNull: false,
    validate: {
      min: 1
    }
  },
  paymentMethod: {
    type: DataTypes.ENUM('alipay', 'wechat', 'bank_transfer'),
    allowNull: false
  },
  status: {
    type: DataTypes.ENUM('pending', 'paid', 'failed'),
    defaultValue: 'pending'
  },
  paymentId: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  notifyUrl: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  returnUrl: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  callbackData: {
    type: DataTypes.TEXT,
    allowNull: true
  }
}, {
  timestamps: true,
  indexes: [
    {
      fields: ['userId']
    },
    {
      fields: ['orderId']
    },
    {
      fields: ['status']
    },
    {
      fields: ['materialOrderId']
    }
  ]
});

// 建立与 User 模型的关联
Payment.belongsTo(User, { foreignKey: 'userId' });
User.hasMany(Payment, { foreignKey: 'userId' });

// 注意：MaterialOrder 的关联关系在 associations.js 中定义，这里不重复定义

// 同步模型到数据库
const syncPayment = async (force = false) => {
  try {
    await Payment.sync({ force });
    console.log('Payment 模型同步成功');
  } catch (error) {
    console.error('Payment 模型同步失败:', error);
  }
};

module.exports = {
  Payment,
  syncPayment
};